package org.hhf.ai.service;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * 数据缓存队列，队列中数据只保留最新的maxSize条
 * @param <E>
 */
public class FixedSizeQueue<E> extends LinkedBlockingQueue<E> {
    private final int maxSize;

    public FixedSizeQueue(int maxSize) {
        super(maxSize);
        this.maxSize = maxSize;
    }

    @Override
    public boolean offer(E e) {
        // 如果队列已满，移除最老的元素
        if (size() >= maxSize) {
            poll(); // 移除队列头部的元素（最老的元素）
        }
        return super.offer(e);
    }

    public static void main(String[] args) {
        FixedSizeQueue<Integer> queue = new FixedSizeQueue<>(5);

        for (int i = 1; i <= 10; i++) {
            queue.offer(i);
            System.out.println("Added: " + i + ", Queue: " + queue);
        }
    }
}